<template>
	<view class="bg-white">
		<view>
			<action-bar :isBack="false" title="授权登录"></action-bar>
		</view>
		<view class="container padding text-center">
			<form v-if="isT">
				<view class="text-container">
					<text class="bg-grey text-lg">测试阶段，建议使用测试账号进行测试</text>
					<text class="text-lg margin-tb-sm">选择一个测试账户登陆:</text>
					<view style="margin-top: 100rpx;">
						<button class="cu-btn bg-brown" @click="testLogin('root')">ROOT用户</button>
						<button class="cu-btn bg-blue margin-lr-xl" @click="testLogin('admin')">ADMIN用户</button>
						<button class="cu-btn bg-green" @click="checkLogin()">微信登陆</button>
					</view>
				</view>
			</form>
			
			<view v-if="!isT" style="margin: auto;">
				<view>
					<view class="cu-avatar lg round" :style="avatarBgUrl"></view>
					<view class="text-black" v-text="nickname"></view>
				</view>
				<!-- needAuth未发生改变 -->
				<view v-if="needAuth == null" class="margin-top-sm">
					网络请求超时
				</view>
				<!-- needAuth发生变动 -->
				<view v-else class="margin-top-sm">
					<button 
						@click="authLogin()"
						class="cu-btn bg-red margin-tb-sm lg round">
						<view v-if="needAuth && isInvite">微信授权登录, 加入他人账本</view>
						<view v-else-if="needAuth">微信授权登录</view>
						<view v-else>登录中...</view>
					</button>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import {mapGetters} from 'vuex'
	import {parseSceneToJson} from '../../common/base.js'
	export default {
		data() {
			return {
				isT: true,
				token: null,
				needAuth: null,
				scene: null,
				isInvite: false,   		// 是否是被邀请
				inviteParams: '',
				inviteJSONParams: {},
				msg: '',
				StatusBar: this.StatusBar,
				test: {
					token: '',
					query: ''
				},
				
			}
		},
		computed: {
			...mapGetters(['avatarBgUrl', 'url'])
		},
		onLoad(query) {
			// console.log('query params: ', query)
			// console.log(decodeURIComponent(query.scene))
			
			// wx.login()  -> 获取code
			// 向微信服务器发送请求  -> 获取openId
			uni.showLoading({title: '加载中'})
			
			this.getPermissions()
			
			// query中有参数, 说明是通过扫码进入到的系统
			if (query && JSON.stringify(query) != '{}') {
				console.log('%c解析到邀请参数', 'color: green;font-size: 20px')
				// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的scene
				this.inviteParams = decodeURIComponent(query.scene)  // uid=1&bid=2&s=invite
				console.log(`%c${this.inviteParams}`, 'color: green;font-size: 20px')
				
				this.inviteJSONParams = parseSceneToJson(this.inviteParams)  // {uid: 1}
				this.isInvite = true
				// scene中有数据，访问模式为扫描他人二维码，进行自动注册
				// 保存邀请信息
			}
			
			// 测试代码片段
			if (this.isT) {
				uni.hideLoading()
				console.warn('page/index/index暂停了onload()事件的执行，调试完成之后请将屏蔽代码删除');
				return;
			}
			
			// 检查用户授权状态
			this.checkLogin()
		},
		methods: {
			testChange(e) {
				this.test.token = e.detail.value
			},
			testLogin(status) {
				
				if (status == 'real') {
					uni.showModal({
						title: '微信登陆暂未开放!'
					})
					return
				}
				
				this.$request({
					url: `/wx/test/login/${status}`
				}).then((res) => {
					if (res && res.data.code == 200) {  // 用户已经授权
						this.needAuth = false
						this.$store.commit('setUserToken', res.data.token)
						this.$store.commit('setUserInfo', res.data.userInfo)
						this.redirectToIndexPage()  // 页面跳转
					} else { // 用户未授权
						this.needAuth = true
					}
				})
			},
			
			/**
			 * 检查授权登录状态
			 */
			checkLogin() {
				uni.showLoading({title: '登录检查中'})
				this.wxGetCode().then(res => {
					this.$request({url: `/wx/login/${res.code}`}).then(res => {
						if (res && res.data.code == 200) {  // 用户已经授权
							this.needAuth = false
							this.$store.commit('setUserToken', res.data.token)
							this.$store.commit('setUserInfo', res.data.userInfo)
							this.redirectToIndexPage()  // 页面跳转
						} else { // 用户未授权
							this.needAuth = true
						}
					})
				})
			},
			
			/**
			 * 授权登录, 204 8848
			 */
			authLogin() {
				uni.hideLoading()
				this.wxGetAuthInfo().then(res => {
					uni.showLoading({url: '登录中'})
					var userInfo = res.userInfo  // 用户数据
					this.$store.commit('setUserInfo', res.userInfo)
					this.wxGetCode().then(res => {
						userInfo.code = res.code
						this.$request({url: '/wx/save', method: 'POST', data: userInfo}).then(res => {
							if (res && res.data.code === 200) {
								this.$store.commit('setUserToken', res.data.token);  // 保存用户令牌
								this.redirectToIndexPage()  // 页面跳转
							}
						})
					})
				})
			},
			
			/**
			 * 用户邀请操作
			 */
			invite() {
				console.debug('开始邀请流程...');
				// 保存邀请信息
				let info = this.inviteJSONParams
				if (info.uid == this.$store.getters.id) {  // 扫描了自己的邀请码
					this.$message.info('您已经存在当前账本中了!')
					setTimeout(() => {
						this.nomalRedirect()
					}, 1000)
					return
				}
				
				// 保存邀请信息
				this.$request({
					url: `/account/${info.bid}/${this.$store.getters.id}/invite/${info.uid}`,
					method: 'POST',
					data: {
						'userId': this.$store.getters.id,
						'bookId': info.bid,
						'inviteUserId': info.uid
					}
				}).then(res => {
					if (res && res.data.code == 200) {
						uni.redirectTo({url: `../book/index?m=invite&bid=${info.bid}`})
						uni.hideLoading()
					} else if (res && res.data.message === '数据库中已存在该记录') {
						uni.redirectTo({url: `../book/index?m=invite&bid=${info.bid}`})
						uni.hideLoading()
					} else if (res) {
						this.$message.error(res.data.message)
					}
				})
			},
			
			/**
			 * 获取微信用户信息
			 */
			wxGetAuthInfo() {
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						lang: 'zh_CN',
						desc: '获取用户昵称头像信息',
						provider: 'weixin',
						success: res => {
							resolve(res)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			
			/**
			 * 获取微信登录凭证
			 */
			wxGetCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						success: res => {
							resolve(res);
						},
						fail: err => {
							reject(err);
						}
					})
				})
			},
			
			/**
			 * 用户登录成功后，判断是否被邀请，如果被邀请，则执行相应操作
			 * scene=uidE1AbidE1AsEinvite
			 */
			redirectToIndexPage() {
				if(this.isInvite) {
					uni.hideLoading()
					this.invite()
				} else {
					this.nomalRedirect()
				}
			},
			
			/**
			 * 普通用户跳转
			 */
			nomalRedirect() {
				uni.redirectTo({url: '../book/index'})
				uni.hideLoading()
			},
			getPermissions() {
				this.$request({
					url: '/user/rights'
				}).then(res => {
					this.$store.commit("setRightMenus", res.data.rights)
				})
			},
		}
	}
</script>

<style>
	
	.container {
		width: 100vw;
		height: 100vh;
		
		display: flex;
	}
	
	.textBox {
		text-align: left;
	}
	
	.text-container {
		margin-top: 300rpx;
		display: flex;
		flex-direction: column;
	}
</style>
